import libtcodpy as libtcod
import events	
	
class InputEvent(object):
	def __init__(self):
		self.dispatched = False
			
	def dispatch(self):
		self.dispatched = True
		
class MouseInputEvent(InputEvent):
	def __init__(self, x, y, _type = "lmb"):
		super(MouseInputEvent,self).__init__()
		
		self.x = x
		self.y = y
		self._type = _type



class InputController(events.EventListener):
	
	def __init__(self):
		super(InputController,self).__init__()
		
		self.last_action = ""

	def handle_keys(self):
		action = self.get_action()
		self.last_action = action
		
		return action
		
	def get_action(self):
		
		game_state = 'playing'	#hack hack hack
		
		
		player = self.em.services["player"]
		render = self.em.services["render"]
		viewport = render.viewport
		
		key = libtcod.console_check_for_keypress(libtcod.KEY_PRESSED)
		mouse = libtcod.mouse_get_status()
		if mouse.lbutton_pressed:
			#render.describe_tile(game_map, mouse.cx, mouse.cy)
			render.e_input_event(MouseInputEvent(mouse.cx,mouse.cy,"lmb"))
			
		if mouse.rbutton_pressed:
			#render.context_menu(game_map, mouse.cx, mouse.cy)
			render.e_input_event(MouseInputEvent(mouse.cx,mouse.cy,"rmb"))
		
		render.e_input_event(MouseInputEvent(mouse.cx,mouse.cy,"idle"))
		
		if key.vk == libtcod.KEY_ENTER and key.lalt:
			libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())
			
		elif key.vk == libtcod.KEY_ESCAPE:
			return 'exit'
			
		if game_state == 'playing' and player.is_alive():	
			#if libtcod.console_is_key_pressed(libtcod.KEY_UP):
			if key.vk == libtcod.KEY_UP or key.c == ord('w'):
				player.move(0,-1)
				viewport.locate(player.x,player.y)
				
			elif key.vk == libtcod.KEY_DOWN or key.c == ord('s'):
				player.move(0,1)
				viewport.locate(player.x,player.y)
				
			elif key.vk == libtcod.KEY_LEFT or key.c == ord('a'):
				player.move(-1,0)
				viewport.locate(player.x,player.y)
				
			elif key.vk == libtcod.KEY_RIGHT or key.c == ord('d'):
				player.move(1,0)
				viewport.locate(player.x,player.y)
			
			elif key.vk == libtcod.KEY_SPACE:
				pass
				
			elif key.vk == libtcod.KEY_TAB:
				render.e_kb_tab()
				return 'didnt-take-turn'
				
			else:
				return 'didnt-take-turn'
			
	def invalidate_fov(self):
		pass
